import 'dart:async';
import 'dart:developer';
import 'dart:convert';
import 'package:base_flutter/src/network/config.dart';
import 'package:dio/dio.dart';
import 'package:flutter/foundation.dart';
import 'package:base_flutter/src/network/network_exception.dart';

// 自定义网络异常类
export 'network_exception.dart';

// 定义网络请求状态
enum RequestStatus {
  none,
  loading,
  success,
  error,
}

// 创建请求取消令牌管理器
class CancelTokenManager {
  final Map<String, CancelToken> _cancelTokens = {};

  // 获取或创建取消令牌
  CancelToken getCancelToken(String requestId) {
    if (!_cancelTokens.containsKey(requestId)) {
      _cancelTokens[requestId] = CancelToken();
    }
    return _cancelTokens[requestId]!;
  }

  // 取消特定请求
  void cancelRequest(String requestId, [String? reason]) {
    if (_cancelTokens.containsKey(requestId)) {
      _cancelTokens[requestId]?.cancel(reason);
      _cancelTokens.remove(requestId);
    }
  }

  // 取消所有请求
  void cancelAllRequests([String? reason]) {
    _cancelTokens.forEach((key, token) {
      token.cancel(reason);
    });
    _cancelTokens.clear();
  }
}

typedef SuccessCallback = Function(dynamic data);
typedef ErrorCallback = Function(Exception e);

class NetworkManager {
  static final NetworkManager _singleton = NetworkManager._internal();

  factory NetworkManager() => _singleton;

  Dio? _dio;
  final CancelTokenManager _cancelTokenManager = CancelTokenManager();

  NetworkManager._internal() {
    _dio ??= Dio();
  }

  init(String baseUrl, {NetworkConfig config = const NetworkConfig()}) {
    _dio!.options.baseUrl = baseUrl;
    _dio!.options.connectTimeout = config.connectTimeout;
    _dio!.options.receiveTimeout = config.receiveTimeout;
    _dio!.options.sendTimeout = config.sendTimeout;
    _dio!.options.contentType = config.contentType;
    
    // 添加认证拦截器
    _dio!.interceptors.add(AuthInterceptor());
    
    // 添加自定义日志拦截器，更详细地记录请求和响应
    _dio!.interceptors.add(CustomLogInterceptor());
    
    // 添加重试拦截器
    _dio!.interceptors.add(RetryInterceptor(_dio!));
  }


  setBaseUrl(String url) {
    _dio!.options.baseUrl = url;
  }

  setHeaders(String key, dynamic value) {
    _dio!.options.headers[key] = value;
    log('Set header $key: $value', level: 0, name: "NETWORK_MANAGER");
  }

  addInterceptor(Interceptor interceptor) {
    _dio?.interceptors.add(interceptor);
  }

  // 设置额外参数
  void setExtra(String key, dynamic value) {
    if (_dio != null) {
      _dio!.options.extra[key] = value;
      log('Set extra $key: $value', level: 0, name: "NETWORK_MANAGER");
    }
  }

  // 取消请求的方法
  void cancelRequest(String requestId, [String? reason]) {
    _cancelTokenManager.cancelRequest(requestId, reason);
  }

  void cancelAllRequests([String? reason]) {
    _cancelTokenManager.cancelAllRequests(reason);
  }

  // 删除未使用的 isConnected() 方法

  /// use catchError carry error.
  Future<T> get<T>(String path,
      {
        Map<String, dynamic>? params,
        String contentType = Headers.jsonContentType,
        bool showResponseMessage = true,
        int retryCount = 2, // 默认重试次数
        int retryDelayMs = 1000, // 默认重试延迟
        String? requestId,
      }) async {
    Completer<T> completer = Completer();
    if (_dio!.options.baseUrl.isEmpty) {
      completer.completeError(Exception(
          "Must be call init() and set valid baseUrl before request"));
    }
    _dio!.options.contentType = contentType;
    
    int currentRetry = 0;
    bool shouldRetry(int retryAttempt) {
      return retryAttempt <= retryCount;
    }

    // 实现重试逻辑
    Future<void> attemptRequest() async {
      try {
        var response = await _dio?.get(
          path, 
          queryParameters: params,
          cancelToken: requestId != null ? _cancelTokenManager.getCancelToken(requestId) : null,
        );
        log("request api success ${response!.data}",
            level: 0, name: "ApiManager");
        
        // 首先检查HTTP状态码是否为200
        if (response.statusCode != 200) {
          completer.completeError(ServerException(
            message: 'HTTP请求失败',
            statusCode: response.statusCode,
            data: response.data
          ));
          return;
        }
        
        var data = response.data;
        // 检查响应体中的code字段
        if (data != null && data is Map) {
          // 业务码为0或200表示成功
          if (data["code"] == 0 || data["code"] == 200) {
            completer.complete(data as T);
          } else {
            // 业务码不为成功状态，抛出BusinessException
            String errorMessage = '业务请求失败';
            if (data.containsKey('message')) {
              errorMessage = data['message']?.toString() ?? errorMessage;
            } else if (data.containsKey('msg')) {
              errorMessage = data['msg']?.toString() ?? errorMessage;
            }
            completer.completeError(BusinessException(
              message: errorMessage,
              errorCode: data["code"]?.toString(),
              data: data
            ));
          }
        } else {
          // 返回成功但带上原始数据
          completer.complete(data as T);
        }
      } on Exception catch (e) {
        if (e is DioException) {
          // 判断是否应该重试
          if ((e.type == DioExceptionType.connectionTimeout || 
               e.type == DioExceptionType.sendTimeout ||
               e.type == DioExceptionType.receiveTimeout ||
               e.type == DioExceptionType.connectionError) && 
              shouldRetry(currentRetry)) {
            currentRetry++;
            log("Request failed, retrying ($currentRetry/$retryCount)...", level: 10, name: "ApiManager");
            // 延迟后重试
            await Future.delayed(Duration(milliseconds: retryDelayMs));
            await attemptRequest();
            return;
          } else {
            // 根据错误类型提供更具体的错误信息
            Exception exception;
            switch (e.type) {
              case DioExceptionType.connectionTimeout:
              case DioExceptionType.sendTimeout:
              case DioExceptionType.receiveTimeout:
                exception = ConnectionTimeoutException(message: e.message ?? '连接超时，请检查网络或稍后重试');
                break;
              case DioExceptionType.connectionError:
                exception = NetworkConnectionException(message: e.message ?? '网络连接错误，请检查网络连接');
                break;
              case DioExceptionType.badResponse:
                // 根据HTTP状态码区分不同的服务器错误
                if (e.response?.statusCode == 401) {
                  exception = const AuthException(message: '授权失败，请重新登录');
                } else if (e.response?.statusCode == 403) {
                  exception = const AuthException(message: '没有权限访问该资源');
                } else if (e.response?.statusCode == 404) {
                  exception = ServerException(
                    message: '请求的资源不存在', 
                    statusCode: e.response?.statusCode,
                    data: e.response?.data
                  );
                    } else if (e.response?.statusCode == 500) {
                      exception = ServerException(
                        message: '服务器内部错误', 
                        statusCode: e.response?.statusCode,
                        data: e.response?.data
                      );
                    } else {
                      exception = ServerException(
                        message: e.message ?? '服务器返回错误', 
                        statusCode: e.response?.statusCode,
                        data: e.response?.data
                      );
                    }
                    break;
                  case DioExceptionType.cancel:
                    exception = RequestCancelledException();
                    break;
                  case DioExceptionType.badCertificate:
                    exception = ServerException(message: '证书验证失败');
                    break;
                  case DioExceptionType.unknown:
                    exception = NetworkException(message: e.message ?? '未知网络错误');
                    break;
                  default:
                    exception = NetworkException(message: e.message ?? '网络请求错误');
                }
                completer.completeError(exception);
          }
        } else {
          completer.completeError(e);
        }
        if (showResponseMessage) {
          // SmartDialog.showToast("请求失敗!請重試");
        }
        log("request exception", level: 10, name: "ApiManager", error: e);
      } on Error catch (e) {
        completer.completeError(e);
        log("Get request error", level: 10, name: "ApiManager", error: e);
        if (showResponseMessage) {
          // SmartDialog.showToast("请求失敗!請重試");
        }
      }
    }

    await attemptRequest();
    return completer.future;
  }

  /// use catchError carry error.
  Future<T> post<T>(String path,
      {
        dynamic data, // 允许传递FormData或Map
        String contentType = Headers.jsonContentType,
        bool showResponseMessage = true,
        int retryCount = 2, // 默认重试次数
        int retryDelayMs = 1000, // 默认重试延迟
        String? requestId,
      }) async {
    Completer<T> completer = Completer();
    if (_dio!.options.baseUrl.isEmpty) {
      completer.completeError(Exception(
          "Must be call init() and set valid baseUrl before request"));
    }
    _dio!.options.contentType = contentType;
    
    int currentRetry = 0;
    bool shouldRetry(int retryAttempt) {
      return retryAttempt <= retryCount;
    }

    // 实现重试逻辑
    Future<void> attemptRequest() async {
      try {
        var response = await _dio?.post(
          path, 
          data: data, // 使用data参数而不是params
          cancelToken: requestId != null ? _cancelTokenManager.getCancelToken(requestId) : null,
        );
        log("Post request success", level: 0, name: "ApiManager");
        
        // 首先检查HTTP状态码是否为200
        if (response!.statusCode != 200) {
          completer.completeError(ServerException(
            message: 'HTTP请求失败',
            statusCode: response.statusCode,
            data: response.data
          ));
          return;
        }
        
        var responseData = response.data; // 重命名变量避免冲突
        // 检查响应体中的code字段
        if (responseData != null && responseData is Map) {
          // 业务码为0或200表示成功
          if (responseData["code"] == 0 || responseData["code"] == 200) {
            completer.complete(responseData as T);
          } else {
            // 业务码不为成功状态，抛出BusinessException
            String errorMessage = '业务请求失败';
            if (responseData.containsKey('message')) {
              errorMessage = responseData['message']?.toString() ?? errorMessage;
            } else if (responseData.containsKey('msg')) {
              errorMessage = responseData['msg']?.toString() ?? errorMessage;
            }
            completer.completeError(BusinessException(
              message: errorMessage,
              errorCode: responseData["code"]?.toString(),
              data: responseData
            ));
          }
        } else {
          // 返回成功但带上原始数据
          completer.complete(responseData as T);
        }
      } on Exception catch (e) {
        if (e is DioException) {
          // 判断是否应该重试
          if ((e.type == DioExceptionType.connectionTimeout || 
               e.type == DioExceptionType.sendTimeout ||
               e.type == DioExceptionType.receiveTimeout ||
               e.type == DioExceptionType.connectionError) && 
              shouldRetry(currentRetry)) {
            currentRetry++;
            log("Request failed, retrying ($currentRetry/$retryCount)...", level: 10, name: "ApiManager");
            // 延迟后重试
            await Future.delayed(Duration(milliseconds: retryDelayMs));
            await attemptRequest();
            return;
          } else {
            // 根据错误类型提供更具体的错误信息
            Exception exception;
            switch (e.type) {
              case DioExceptionType.connectionTimeout:
              case DioExceptionType.sendTimeout:
              case DioExceptionType.receiveTimeout:
                exception = ConnectionTimeoutException(message: e.message ?? '连接超时，请检查网络或稍后重试');
                break;
              case DioExceptionType.connectionError:
                exception = NetworkConnectionException(message: e.message ?? '网络连接错误，请检查网络连接');
                break;
              case DioExceptionType.badResponse:
                // 根据HTTP状态码区分不同的服务器错误
                if (e.response?.statusCode == 401) {
                  exception = const AuthException(message: '授权失败，请重新登录');
                } else if (e.response?.statusCode == 403) {
                  exception = const AuthException(message: '没有权限访问该资源');
                } else if (e.response?.statusCode == 404) {
                  exception = ServerException(
                    message: '请求的资源不存在', 
                    statusCode: e.response?.statusCode,
                    data: e.response?.data
                  );
                    } else if (e.response?.statusCode == 500) {
                      exception = ServerException(
                        message: '服务器内部错误', 
                        statusCode: e.response?.statusCode,
                        data: e.response?.data
                      );
                    } else {
                      exception = ServerException(
                        message: e.message ?? '服务器返回错误', 
                        statusCode: e.response?.statusCode,
                        data: e.response?.data
                      );
                    }
                    break;
                  case DioExceptionType.cancel:
                    exception = RequestCancelledException();
                    break;
                  case DioExceptionType.badCertificate:
                    exception = ServerException(message: '证书验证失败');
                    break;
                  case DioExceptionType.unknown:
                    exception = NetworkException(message: e.message ?? '未知网络错误');
                    break;
                  default:
                    exception = NetworkException(message: e.message ?? '网络请求错误');
                }
                completer.completeError(exception);
          }
        } else {
          completer.completeError(e);
        }
        log("Post request exception", level: 10, name: "ApiManager", error: e);
        if (showResponseMessage) {
          // SmartDialog.showToast("请求失敗!請重試");
        }
      } on Error catch (e) {
        completer.completeError(e);
        log("Post request error", level: 10, name: "ApiManager", error: e);
        if (showResponseMessage) {
          // SmartDialog.showToast("请求失敗!請重試");
        }
      }
    }

    await attemptRequest();
    return completer.future;
  }

  /// PUT请求方法
  Future<T> put<T>(String path,
      {
        dynamic data,
        String contentType = Headers.jsonContentType,
        bool showResponseMessage = true,
        int retryCount = 2,
        int retryDelayMs = 1000,
        String? requestId,
      }) async {
    Completer<T> completer = Completer();
    if (_dio!.options.baseUrl.isEmpty) {
      completer.completeError(Exception(
          "Must be call init() and set valid baseUrl before request"));
    }
    _dio!.options.contentType = contentType;
    
    int currentRetry = 0;
    bool shouldRetry(int retryAttempt) {
      return retryAttempt <= retryCount;
    }

    Future<void> attemptRequest() async {
      try {
        var response = await _dio?.put(
          path, 
          data: data,
          cancelToken: requestId != null ? _cancelTokenManager.getCancelToken(requestId) : null,
        );
        log("Put request success", level: 0, name: "ApiManager");
        
        if (response!.statusCode != 200) {
          completer.completeError(ServerException(
            message: 'HTTP请求失败',
            statusCode: response.statusCode,
            data: response.data
          ));
          return;
        }
        
        var responseData = response.data;
        if (responseData != null && responseData is Map) {
          int? code = responseData['code'];
          if (code != null && code != 200 && code != 0) {
            completer.completeError(BusinessException(
              message: responseData['message'] ?? '请求失败',
              errorCode: code.toString(),
              data: responseData['data']
            ));
            return;
          }
        }
        
        completer.complete(responseData as T);
      } catch (e) {
        currentRetry++;
        if (e is DioException && shouldRetry(currentRetry)) {
          log("Request failed, retrying ($currentRetry/$retryCount)...", level: 10, name: "ApiManager");
          await Future.delayed(Duration(milliseconds: retryDelayMs));
          await attemptRequest();
          return;
        } else {
          Exception exception;
          if (e is DioException) {
            switch (e.type) {
              case DioExceptionType.connectionTimeout:
              case DioExceptionType.sendTimeout:
              case DioExceptionType.receiveTimeout:
                exception = ConnectionTimeoutException(message: e.message ?? '连接超时，请检查网络或稍后重试');
                break;
              case DioExceptionType.connectionError:
                exception = NetworkConnectionException(message: e.message ?? '网络连接错误，请检查网络连接');
                break;
              case DioExceptionType.badResponse:
                if (e.response?.statusCode == 401) {
                  exception = const AuthException(message: '授权失败，请重新登录');
                } else if (e.response?.statusCode == 403) {
                  exception = const AuthException(message: '没有权限访问该资源');
                } else if (e.response?.statusCode == 404) {
                  exception = ServerException(
                    message: '请求的资源不存在', 
                    statusCode: e.response?.statusCode,
                    data: e.response?.data
                  );
                } else if (e.response?.statusCode == 500) {
                  exception = ServerException(
                    message: '服务器内部错误', 
                    statusCode: e.response?.statusCode,
                    data: e.response?.data
                  );
                } else {
                  exception = ServerException(
                    message: '服务器错误', 
                    statusCode: e.response?.statusCode,
                    data: e.response?.data
                  );
                }
                break;
              default:
                exception = NetworkException(message: e.message ?? '网络请求失败');
            }
          } else {
            exception = NetworkException(message: e.toString());
          }
          completer.completeError(exception);
        }
      }
    }

    await attemptRequest();
    return completer.future;
  }

  /// DELETE请求方法
  Future<T> delete<T>(String path,
      {
        String contentType = Headers.jsonContentType,
        bool showResponseMessage = true,
        int retryCount = 2,
        int retryDelayMs = 1000,
        String? requestId,
      }) async {
    Completer<T> completer = Completer();
    if (_dio!.options.baseUrl.isEmpty) {
      completer.completeError(Exception(
          "Must be call init() and set valid baseUrl before request"));
    }
    _dio!.options.contentType = contentType;
    
    int currentRetry = 0;
    bool shouldRetry(int retryAttempt) {
      return retryAttempt <= retryCount;
    }

    Future<void> attemptRequest() async {
      try {
        var response = await _dio?.delete(
          path, 
          cancelToken: requestId != null ? _cancelTokenManager.getCancelToken(requestId) : null,
        );
        log("Delete request success", level: 0, name: "ApiManager");
        
        if (response!.statusCode != 200) {
          completer.completeError(ServerException(
            message: 'HTTP请求失败',
            statusCode: response.statusCode,
            data: response.data
          ));
          return;
        }
        
        var responseData = response.data;
        if (responseData != null && responseData is Map) {
          int? code = responseData['code'];
          if (code != null && code != 200 && code != 0) {
            completer.completeError(BusinessException(
              message: responseData['message'] ?? '请求失败',
              errorCode: code.toString(),
              data: responseData['data']
            ));
            return;
          }
        }
        
        completer.complete(responseData as T);
      } catch (e) {
        currentRetry++;
        if (e is DioException && shouldRetry(currentRetry)) {
          log("Request failed, retrying ($currentRetry/$retryCount)...", level: 10, name: "ApiManager");
          await Future.delayed(Duration(milliseconds: retryDelayMs));
          await attemptRequest();
          return;
        } else {
          Exception exception;
          if (e is DioException) {
            switch (e.type) {
              case DioExceptionType.connectionTimeout:
              case DioExceptionType.sendTimeout:
              case DioExceptionType.receiveTimeout:
                exception = ConnectionTimeoutException(message: e.message ?? '连接超时，请检查网络或稍后重试');
                break;
              case DioExceptionType.connectionError:
                exception = NetworkConnectionException(message: e.message ?? '网络连接错误，请检查网络连接');
                break;
              case DioExceptionType.badResponse:
                if (e.response?.statusCode == 401) {
                  exception = const AuthException(message: '授权失败，请重新登录');
                } else if (e.response?.statusCode == 403) {
                  exception = const AuthException(message: '没有权限访问该资源');
                } else if (e.response?.statusCode == 404) {
                  exception = ServerException(
                    message: '请求的资源不存在', 
                    statusCode: e.response?.statusCode,
                    data: e.response?.data
                  );
                } else if (e.response?.statusCode == 500) {
                  exception = ServerException(
                    message: '服务器内部错误', 
                    statusCode: e.response?.statusCode,
                    data: e.response?.data
                  );
                } else {
                  exception = ServerException(
                    message: '服务器错误', 
                    statusCode: e.response?.statusCode,
                    data: e.response?.data
                  );
                }
                break;
              default:
                exception = NetworkException(message: e.message ?? '网络请求失败');
            }
          } else {
            exception = NetworkException(message: e.toString());
          }
          completer.completeError(exception);
        }
      }
    }

    await attemptRequest();
    return completer.future;
  }
}

class RetryInterceptor extends Interceptor {
  final Dio _dio;
  
  RetryInterceptor(this._dio);
  
  @override
  void onError(DioException err, ErrorInterceptorHandler handler) async {
    if (err.type == DioExceptionType.connectionTimeout ||
        err.type == DioExceptionType.sendTimeout ||
        err.type == DioExceptionType.receiveTimeout ||
        err.type == DioExceptionType.connectionError) {
      
      // 获取重试次数
      final retryCount = (err.requestOptions.extra['retryCount'] as int?) ?? 0;
      final maxRetries = (err.requestOptions.extra['maxRetries'] as int?) ?? 2;
      
      if (retryCount < maxRetries) {
        // 增加重试次数
        err.requestOptions.extra['retryCount'] = retryCount + 1;
        
        // 延迟后重试
        await Future.delayed(Duration(milliseconds: 1000 * (retryCount + 1)));
        
        try {
          final response = await _dio.fetch(err.requestOptions);
          handler.resolve(response);
          return;
        } catch (e) {
          // 重试失败，继续处理错误
        }
      }
    }
    
    handler.next(err);
  }
}

class AuthInterceptor extends Interceptor {
  @override
  void onRequest(RequestOptions options, RequestInterceptorHandler handler) {
    // 确保Authorization头存在且有效
    if (options.headers['Authorization'] == null || 
        !options.headers['Authorization'].toString().startsWith('Bearer ')) {
      // 尝试从Dio实例的options中获取Authorization头
      if (options.extra['Authorization'] != null) {
        options.headers['Authorization'] = options.extra['Authorization'];
        log('AUTH_INTERCEPTOR: Added Authorization header from extra', 
            level: 0, name: "AuthInterceptor");
      } else {
        log('AUTH_INTERCEPTOR: No Authorization header found', 
            level: 1, name: "AuthInterceptor");
      }
    } else {
      log('AUTH_INTERCEPTOR: Valid Authorization header already exists', 
          level: 0, name: "AuthInterceptor");
    }
    
    super.onRequest(options, handler);
  }
}

class CustomLogInterceptor extends Interceptor {
  static const String _tag = "ApiRequestLogger";
  static const String _separator = "--------------------";
  static const String _lineSeparator = "\n";

  @override
  void onRequest(RequestOptions options, RequestInterceptorHandler handler) {
    if (kDebugMode) {
      _logRequest(options);
    }
    super.onRequest(options, handler);
  }

  @override
  void onResponse(Response response, ResponseInterceptorHandler handler) {
    if (kDebugMode) {
      _logResponse(response);
    }
    super.onResponse(response, handler);
  }

  @override
  void onError(DioException err, ErrorInterceptorHandler handler) {
    if (kDebugMode) {
      _logError(err);
    }
    super.onError(err, handler);
  }

  void _logRequest(RequestOptions options) {
    StringBuffer logBuffer = StringBuffer();
    
    logBuffer.write(_lineSeparator);
    logBuffer.write(_separator);
    logBuffer.write(_lineSeparator);
    logBuffer.write("📤 API REQUEST [${options.method}]");
    logBuffer.write(_lineSeparator);
    logBuffer.write("URL: ${options.baseUrl}${options.path}");
    logBuffer.write(_lineSeparator);
    
    // 打印请求头
    if (options.headers.isNotEmpty) {
      logBuffer.write("Headers:");
      options.headers.forEach((key, value) {
        logBuffer.write(_lineSeparator);
        logBuffer.write("  $key: $value");
      });
      logBuffer.write(_lineSeparator);
    }
    
    // 打印查询参数
    if (options.queryParameters.isNotEmpty) {
      logBuffer.write("Query Parameters:");
      logBuffer.write(_lineSeparator);
      logBuffer.write(_formatJson(options.queryParameters));
      logBuffer.write(_lineSeparator);
    }
    
    // 打印请求体
    if (options.data != null) {
      logBuffer.write("Request Body:");
      logBuffer.write(_lineSeparator);
      if (options.data is Map) {
        logBuffer.write(_formatJson(options.data));
      } else {
        logBuffer.write(options.data.toString());
      }
      logBuffer.write(_lineSeparator);
    }
    
    logBuffer.write(_separator);
    logBuffer.write(_lineSeparator);
    
    log(logBuffer.toString(), name: _tag);
  }

  void _logResponse(Response response) {
    StringBuffer logBuffer = StringBuffer();
    
    logBuffer.write(_lineSeparator);
    logBuffer.write(_separator);
    logBuffer.write(_lineSeparator);
    logBuffer.write("📥 API RESPONSE [${response.statusCode}] ${response.requestOptions.method}");
    logBuffer.write(_lineSeparator);
    logBuffer.write("URL: ${response.requestOptions.baseUrl}${response.requestOptions.path}");
    logBuffer.write(_lineSeparator);
    
    // 打印响应时间（避免解析非ISO日期格式导致异常）
    final dateHeader = response.headers.value('date');
    if (dateHeader != null) {
      try {
        // 有些服务器返回RFC1123格式日期，直接打印以避免解析错误
        logBuffer.write("Date: $dateHeader");
        logBuffer.write(_lineSeparator);
      } catch (_) {
        // 忽略解析错误
      }
    }
    
    // 打印响应体
    if (response.data != null) {
      logBuffer.write("Response Body:");
      logBuffer.write(_lineSeparator);
      if (response.data is Map || response.data is List) {
        logBuffer.write(_formatJson(response.data));
      } else {
        logBuffer.write(response.data.toString());
      }
      logBuffer.write(_lineSeparator);
    }
    
    logBuffer.write(_separator);
    logBuffer.write(_lineSeparator);
    
    log(logBuffer.toString(), name: _tag);
  }

  void _logError(DioException err) {
    StringBuffer logBuffer = StringBuffer();
    
    logBuffer.write(_lineSeparator);
    logBuffer.write(_separator);
    logBuffer.write(_lineSeparator);
    logBuffer.write("❌ API ERROR [${err.type}]");
    logBuffer.write(_lineSeparator);
    
    if (err.requestOptions != null) {
      logBuffer.write("URL: ${err.requestOptions.baseUrl}${err.requestOptions.path}");
      logBuffer.write(_lineSeparator);
    }
    
    logBuffer.write("Error Message: ${err.message}");
    logBuffer.write(_lineSeparator);
    
    if (err.response != null) {
      logBuffer.write("Status Code: ${err.response!.statusCode}");
      logBuffer.write(_lineSeparator);
      logBuffer.write("Response Data:");
      logBuffer.write(_lineSeparator);
      final data = err.response!.data;
      if (data is Map || data is List) {
        logBuffer.write(_formatJson(data));
      } else {
        logBuffer.write(data.toString());
      }
      logBuffer.write(_lineSeparator);
    }
    
    logBuffer.write(_separator);
    logBuffer.write(_lineSeparator);
    
    log(logBuffer.toString(), name: _tag, error: err.stackTrace);
  }

  String _formatJson(dynamic json) {
    try {
      const encoder = JsonEncoder.withIndent('  ');
      return encoder.convert(json);
    } catch (e) {
      return json.toString();
    }
  }
}
